package org.example.service.impl;

import org.example.controller.request.LinkGroupAddRequest;
import org.example.controller.request.LinkGroupUpdateRequest;
import org.example.interceptor.LoginInterceptor;
import org.example.manager.LinkGroupManager;
import org.example.model.LinkGroupDO;
import org.example.service.LinkGroupService;
import org.example.vo.LinkGroupVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 谢超
 * @since 2023-08-15
 */
@Service
public class LinkGroupServiceImpl implements LinkGroupService {

    @Resource
    private LinkGroupManager linkGroupManager;

    @Override
    public int addGroup(LinkGroupAddRequest addRequest) {
        long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();

        LinkGroupDO linkGroupDO = new LinkGroupDO();
        linkGroupDO.setTitle(addRequest.getTitle());
        linkGroupDO.setAccountNo(accountNo);

        return linkGroupManager.addGroup(linkGroupDO);
    }

    @Override
    public int delGroup(long groupId) {
        // 需要根据账号权限进行删除
        long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();

        return linkGroupManager.delGroup(groupId, accountNo);
    }

    @Override
    public LinkGroupVO getGroupDetails(long groupId) {
        long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();
        LinkGroupDO linkGroupDO = linkGroupManager.getGroupDetails(groupId, accountNo);
        LinkGroupVO linkGroupVO = new LinkGroupVO();

        // 将DO数据复制给VO
        BeanUtils.copyProperties(linkGroupDO, linkGroupVO);
        return linkGroupVO;
    }

    @Override
    public List<LinkGroupVO> getAllGroup() {
        long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();
        List<LinkGroupDO> groupListDO = linkGroupManager.getAllGroup(accountNo);
        List<LinkGroupVO> res = groupListDO.stream().map(obj -> {
            LinkGroupVO linkGroupVO = new LinkGroupVO();
            BeanUtils.copyProperties(obj, linkGroupVO);
            return linkGroupVO;
        }).collect(Collectors.toList());
        return res;
    }

    @Override
    public int updateGroupById(LinkGroupUpdateRequest updateRequest) {
        long accountNo = LoginInterceptor.threadLocal.get().getAccountNo();

        LinkGroupDO linkGroupDO = new LinkGroupDO();
        linkGroupDO.setTitle(updateRequest.getTitle());
        linkGroupDO.setId(updateRequest.getId());

        return linkGroupManager.updateGroupById(linkGroupDO, accountNo);
    }
}
